import React, {useEffect, useState} from 'react';
import {Button, Drawer, Icon, Message, Nav} from "@alifd/next";
import {useNavigate, useParams} from "react-router-dom";
import './index.css';
import CodeHighlighter from "../../components/CodeHighlighter";
import ProjectSetting from "./ProjectSetting";

const Index = () => {
    const {Item} = Nav;
    const navigate = useNavigate();

    const loginUser = JSON.parse(window.localStorage.getItem("icip-dingtalk-loginUser")) || "";
    const corpId = window.localStorage.getItem("icip-dingtalk-corpId");
    const {projectId} = useParams();
    const [projectInfo, setProjectInfo] = useState(null)
    const [DATA_VISIBLE, SET_DATA_VISIBLE] = useState(false)

    //展示页
    const [statePage, setStatePage] = useState("bg")

    const [bgData, setBgData] = useState({
        "bgImageZoomMode": "Origin", "bgImageOutputFormat": "jpg"
    });

    const [coverageData, setCoverageData] = useState([]);

    const onChangeData = (itemValue) => {
        console.log("11",coverageData)
        const newCoverageData = coverageData
        let index = newCoverageData.findIndex(element=>element.filedId === itemValue.filedId);
        newCoverageData[index] = itemValue;
        setCoverageData(newCoverageData);
    }

    // eslint-disable-next-line
    useEffect(() => {
        //判断当前localStorage中是否有icip-dingtalk数据，如果没有，则跳转至login页面
        if (!corpId) {
            Message.notice("未获取到当前登录的企业信息！");
            setTimeout(() => {
                navigate("/login")
            }, 1000)
        } else if (!loginUser) {
            Message.notice("未获取到当前登录的用户信息！");
            setTimeout(() => {
                navigate(`/login?corpId=${corpId}`)
            }, 1000)
        } else {
            searchProjectById(projectId);
        }
    }, [projectId, navigate, corpId])

    /**
     * 数据抽屉事件
     */
    const onOpenData = () => {
        SET_DATA_VISIBLE(true)
    };
    const onCloseData = () => {
        SET_DATA_VISIBLE(false)
    };

    const searchProjectById = (projectId) => {
        const myHeaders = new Headers();
        myHeaders.append("Content-Type", "text/plain");

        const requestOptions = {
            method: 'GET', headers: myHeaders, redirect: 'follow'
        };

        fetch(`${window.appConfig.servicePath}/project/searchProjectById?projectId=${projectId}`, requestOptions)
            .then(response => response.json().then(result => setProjectInfo(result)))
            .catch(error => console.log('error', error));
    }

    //随机标识
    const createFiledId = (decimalNumber) => {
        const base = 26;
        let result = '';
        while (decimalNumber > 0) {
            const remainder = decimalNumber % base;
            result = String.fromCharCode(remainder + 65) + result;
            decimalNumber = Math.floor(decimalNumber / base);
        }
        return result;
    }


    const addCoverage = (type) => {
        const filedId = createFiledId(new Date())
        if (type === "text") {
            const newCoverageData = [...coverageData, {
                "type": "Text",
                "variable": false,
                "filedId": `Text_${filedId}`,
                "content": "文本",
                "positionX": 0,
                "positionY": 0,
                "setCenter": false,
                "setColor": "#000000",
                "setFontFamily": "微软雅黑",
                "setBold": false,
                "setStrikeThrough": false,
                "setFontSize": 12,
                "setAutoBreakLine": false,
                "setDirection": "LeftRight",
                "setRepeat": false,
                "setBaseLine": "Top",
                "variableName":`Text_${filedId}`
            }]
            setCoverageData(newCoverageData)
        } else if (type === "image") {
            console.log("image======>",coverageData)
            const newCoverageData = [...coverageData, {
                "setZoom": false,
                "type": "Image",
                "variable": false,
                "filedId": `Image_${filedId}`,
                "positionX": 0,
                "positionY": 0,
                "setCenter": false,
                "setDirection": "LeftRight",
                "setZoom_ZoomMode": "ZoomMode.Origin",
                "setRepeat": false,
                "variableName": `Image_${filedId}`
            }]
            setCoverageData(newCoverageData)
        } else {
            setCoverageData(type)
        }
    }

    return (<div className="projectConfig_Page">
        <div className="projectConfig_Page_Header">
            <div className="projectConfig_Page_Header_ProjectName_Box">
                <Icon type="arrow-left" className="projectConfig_Page_Header_Icon" onClick={() => {
                    navigate("/home/project")
                }}/>
                <div
                    className="projectConfig_Page_Header_ProjectName">{projectInfo ? projectInfo.projectName : ""}</div>
            </div>
            <div className="projectConfig_Page_Header_Button_Box">
                <Button text onClick={onOpenData}>数据</Button>
                <Button text onClick={() => setStatePage("bg")}>背景设置</Button>
                <Button>预览</Button>
                <Button type={"primary"}>保存</Button>
            </div>
        </div>

        <div className={"projectConfig_Page_Content_Box"}>
            <Nav className={"projectConfig_Page_Nav"} type="line" embeddable defaultSelectedKeys={"set"}>
                <Item icon="set" key={"set"}>配置</Item>
                <Item icon="form" key={"doc"}>接口文档</Item>
                <Item icon="list" key={"msg"}>执行日志</Item>
            </Nav>

            <div className={"projectConfig_Page_Content_Content"}>
                <ProjectSetting
                    bgData={bgData}
                    setBgData={setBgData}
                    coverageData={coverageData}
                    addCoverage={addCoverage}
                    statePage={statePage}
                    setStatePage={setStatePage}
                    onChangeData={onChangeData}/>
            </div>
        </div>
        <Drawer
            title="Data"
            placement="right"
            visible={DATA_VISIBLE}
            onClose={onCloseData}
            width={600}
        >
            <h3>背景图片数据：</h3>
            <CodeHighlighter code={JSON.stringify(bgData, null, 2)} language="json"/>
            <h3>图层数据：</h3>
            <CodeHighlighter code={JSON.stringify(coverageData, null, 2)} language="json"/>
        </Drawer>
    </div>);
};

export default Index;